import {
	defineStore
} from 'pinia';
import http from '../common/request'
import useChatStore from './chatStore';
export default defineStore('noticeStore', {
	state: () => {
		return {
			notice: {}
		}
	},
	actions: {
		loadNotice() {
			return new Promise((resolve, reject) => {
				http({
					url: "/systemMessage/findUnReadSystemMessage",
					methods: "GET"
				}).then(res => {
					delete res['53']
					this.notice = res
					if (this.notice) {
						if (this.sum > 0) {
							uni.setTabBarBadge({
								index: 2,
								text: this.sum + ""
							})
						}
					}
					resolve(res)
				}).catch((err) => {
					reject(err)
				})
				this.notice.privateCount = 0
				this.notice.businessCount = 0
				const chatStore = useChatStore()
				
				chatStore.resetFriendBusinessChats()

				// chatStore.privateChats.forEach(item => {
				// 	this.notice.privateCount += item.unreadCount
				// })

				chatStore.friendBusinessChats.forEach(item => {
					this.notice.businessCount += item.unreadCount
				})

				if (this.notice.businessCount > 0) {
					uni.setTabBarBadge({
						index: 1,
						text: this.notice.businessCount + ""
					})
				}


				// if (this.notice.privateCount > 0) {
				// 	uni.setTabBarBadge({
				// 		index: 0,
				// 		text: this.notice.privateCount + ""
				// 	})
				// }

			})
		},
		add(type) {
			this.notice[type] = (this.notice[type] || 0) + 1
		},
		clear() {
			this.notice = {};
			// 清除私人和商业通知计数
			this.notice.privateCount = 0;
			this.notice.businessCount = 0;
			uni.removeTabBarBadge({
				index: 0
			})
			uni.removeTabBarBadge({
				index: 1
			})
			uni.removeTabBarBadge({
				index: 2
			})
		},
	},
	getters: {
		sum: (state) => {
			return (Object.values(state.notice) || []).reduce((x, y) => x + y, 0);
		},
	},
})